<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>手机端调试测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .status.success { background-color: #d4edda; color: #155724; }
        .status.error { background-color: #f8d7da; color: #721c24; }
        .status.info { background-color: #d1ecf1; color: #0c5460; }
        .btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover { background: #0056b3; }
        .btn:disabled { background: #6c757d; cursor: not-allowed; }
        .btn.danger { background: #dc3545; }
        .btn.danger:hover { background: #c82333; }
        .btn.success { background: #28a745; }
        .btn.success:hover { background: #218838; }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }
        .test-section {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 15px;
            margin: 10px 0;
        }
        .test-section h3 {
            margin-top: 0;
            color: #333;
        }
    </style>
</head>
<body>
    <h1>📱 手机端调试测试</h1>
    
    <div class="card">
        <h2>连接状态</h2>
        <div id="connectionStatus" class="status info">正在连接...</div>
        <div id="deviceInfo" class="status info">设备信息加载中...</div>
        <button id="connectBtn" class="btn">连接服务器</button>
        <button id="disconnectBtn" class="btn danger">断开连接</button>
    </div>

    <div class="card">
        <h2>配对状态测试</h2>
        <div class="test-section">
            <h3>当前配对状态</h3>
            <div id="pairingStatus" class="status info">检查中...</div>
            <button id="checkPairingBtn" class="btn">检查配对状态</button>
            <button id="forcePairBtn" class="btn success">强制配对</button>
        </div>
        
        <div class="test-section">
            <h3>设备注册测试</h3>
            <button id="registerDeviceBtn" class="btn">注册设备</button>
            <button id="checkRegistrationBtn" class="btn">检查注册状态</button>
        </div>
    </div>

    <div class="card">
        <h2>语音识别测试</h2>
        <div class="test-section">
            <h3>发送测试请求</h3>
            <button id="sendTestVoiceBtn" class="btn success">发送测试语音请求</button>
            <button id="sendTestTextBtn" class="btn">发送测试文本</button>
        </div>
        
        <div class="test-section">
            <h3>录音测试</h3>
            <button id="startRecordingBtn" class="btn success">开始录音</button>
            <button id="stopRecordingBtn" class="btn danger" disabled>停止录音</button>
            <div id="recordingStatus" class="status info">准备就绪</div>
        </div>
    </div>

    <div class="card">
        <h2>调试日志</h2>
        <button id="clearLogBtn" class="btn">清除日志</button>
        <div id="debugLog" class="log"></div>
    </div>

    <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
    <script>
        // 全局变量
        let socket = null;
        let mediaRecorder = null;
        let isRecording = false;
        let audioChunks = [];

        // DOM 元素
        const connectionStatus = document.getElementById('connectionStatus');
        const deviceInfo = document.getElementById('deviceInfo');
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const pairingStatus = document.getElementById('pairingStatus');
        const checkPairingBtn = document.getElementById('checkPairingBtn');
        const forcePairBtn = document.getElementById('forcePairBtn');
        const registerDeviceBtn = document.getElementById('registerDeviceBtn');
        const checkRegistrationBtn = document.getElementById('checkRegistrationBtn');
        const sendTestVoiceBtn = document.getElementById('sendTestVoiceBtn');
        const sendTestTextBtn = document.getElementById('sendTestTextBtn');
        const startRecordingBtn = document.getElementById('startRecordingBtn');
        const stopRecordingBtn = document.getElementById('stopRecordingBtn');
        const recordingStatus = document.getElementById('recordingStatus');
        const debugLog = document.getElementById('debugLog');
        const clearLogBtn = document.getElementById('clearLogBtn');

        // 日志函数
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = `[${timestamp}] ${message}`;
            debugLog.innerHTML += logEntry + '\n';
            debugLog.scrollTop = debugLog.scrollHeight;
            console.log(logEntry);
        }

        function clearLog() {
            debugLog.innerHTML = '';
        }

        // 连接服务器
        function connectToServer() {
            log('正在连接服务器...');
            
            const serverUrl = window.location.protocol === 'https:' 
                ? 'wss://' + window.location.hostname + ':3001'
                : 'ws://' + window.location.hostname + ':3001';
            
            socket = io(serverUrl, {
                transports: ['websocket', 'polling'],
                timeout: 10000
            });

            socket.on('connect', () => {
                log('✅ 连接成功，Socket ID: ' + socket.id);
                connectionStatus.textContent = '已连接';
                connectionStatus.className = 'status success';
                
                // 注册设备
                registerDevice();
            });

            socket.on('disconnect', (reason) => {
                log('❌ 连接断开: ' + reason);
                connectionStatus.textContent = '连接断开';
                connectionStatus.className = 'status error';
            });

            socket.on('connect_error', (error) => {
                log('❌ 连接错误: ' + error.message);
                connectionStatus.textContent = '连接失败';
                connectionStatus.className = 'status error';
            });

            // 监听所有事件用于调试
            socket.onAny((eventName, ...args) => {
                log(`🔍 收到事件: ${eventName}`, 'debug');
            });
        }

        // 注册设备
        function registerDevice() {
            if (!socket) return;
            
            const deviceInfo = {
                type: 'mobile',
                name: 'Test Mobile Device',
                capabilities: {
                    canSendVoice: true,
                    canReceiveText: false,
                    canGenerateQR: false,
                    canScanQR: true,
                    speechRecognition: true,
                    mediaRecording: true,
                    camera: true,
                    vibration: true
                }
            };

            log('📱 注册设备: ' + JSON.stringify(deviceInfo));
            socket.emit('device:register', deviceInfo);
        }

        // 检查配对状态
        function checkPairingStatus() {
            log('🔍 检查配对状态...');
            
            // 模拟检查配对状态
            const mockPairedDevices = [
                { id: 'test_browser_1', name: 'Test Browser', type: 'browser' }
            ];
            const mockCurrentSession = 'test_session_1';
            
            const isPaired = mockPairedDevices.length > 0 && mockCurrentSession;
            
            log(`配对状态: ${isPaired ? '已配对' : '未配对'}`);
            log(`配对设备数量: ${mockPairedDevices.length}`);
            log(`当前会话: ${mockCurrentSession || '无'}`);
            
            pairingStatus.textContent = isPaired ? '已配对' : '未配对';
            pairingStatus.className = isPaired ? 'status success' : 'status error';
        }

        // 强制配对
        function forcePair() {
            log('🔧 强制配对...');
            
            // 模拟配对成功
            const mockPairingResult = {
                success: true,
                deviceId: 'test_browser_' + Date.now(),
                deviceName: 'Test Browser'
            };
            
            log('模拟配对成功: ' + JSON.stringify(mockPairingResult));
            pairingStatus.textContent = '已配对 (强制)';
            pairingStatus.className = 'status success';
        }

        // 发送测试语音请求
        function sendTestVoiceRequest() {
            if (!socket) {
                log('❌ Socket未连接');
                return;
            }
            
            log('📤 发送测试语音识别请求...');
            
            const testData = {
                audioData: 'data:audio/webm;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbq2EcBj+a2/LDciUFLIHO8tiJNwgZaLvt559NEAxQp+PwtmMcBjiR1/LMeSwFJHfH8N2QQAoUXrTp66hVFApGn+DyvmwhBSuBzvLZiTYIG2m98OScTgwOUarm7blmGgU7k9n1unEiBC13yO/eizEIHWq+8+OWT',
                language: 'zh-CN',
                timestamp: Date.now(),
                options: {
                    provider: 'baidu',
                    format: 'webm'
                }
            };
            
            socket.emit('voice:recognize', testData);
            log('✅ 测试语音识别请求已发送');
        }

        // 发送测试文本
        function sendTestText() {
            if (!socket) {
                log('❌ Socket未连接');
                return;
            }
            
            log('📤 发送测试文本...');
            
            const testData = {
                text: '这是一条测试文本',
                timestamp: Date.now(),
                language: 'zh-CN'
            };
            
            socket.emit('text:input', testData);
            log('✅ 测试文本已发送');
        }

        // 开始录音
        async function startRecording() {
            if (isRecording) return;
            
            try {
                log('🎤 开始录音...');
                
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    audio: {
                        echoCancellation: true,
                        noiseSuppression: true,
                        autoGainControl: true,
                        sampleRate: 16000
                    } 
                });
                
                mediaRecorder = new MediaRecorder(stream, {
                    mimeType: 'audio/webm;codecs=opus'
                });
                
                audioChunks = [];
                
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        audioChunks.push(event.data);
                    }
                };
                
                mediaRecorder.onstop = async () => {
                    log('🎤 录音结束，准备发送...');
                    const audioBlob = new Blob(audioChunks, { type: 'audio/webm;codecs=opus' });
                    
                    // 转换为base64
                    const reader = new FileReader();
                    reader.onload = () => {
                        const base64Data = reader.result;
                        log('📤 发送音频数据...');
                        
                        if (socket) {
                            socket.emit('voice:recognize', {
                                audioData: base64Data,
                                language: 'zh-CN',
                                timestamp: Date.now(),
                                options: {
                                    provider: 'baidu',
                                    format: 'webm'
                                }
                            });
                            log('✅ 音频数据已发送');
                        }
                    };
                    reader.readAsDataURL(audioBlob);
                };
                
                mediaRecorder.start();
                isRecording = true;
                recordingStatus.textContent = '正在录音...';
                recordingStatus.className = 'status info';
                startRecordingBtn.disabled = true;
                stopRecordingBtn.disabled = false;
                
            } catch (error) {
                log('❌ 开始录音失败: ' + error.message);
                recordingStatus.textContent = '录音失败: ' + error.message;
                recordingStatus.className = 'status error';
            }
        }

        // 停止录音
        function stopRecording() {
            if (!isRecording) return;
            
            log('🛑 停止录音...');
            
            if (mediaRecorder && mediaRecorder.state === 'recording') {
                mediaRecorder.stop();
            }
            
            isRecording = false;
            recordingStatus.textContent = '处理中...';
            recordingStatus.className = 'status info';
            startRecordingBtn.disabled = false;
            stopRecordingBtn.disabled = true;
        }

        // 事件监听器
        connectBtn.addEventListener('click', connectToServer);
        disconnectBtn.addEventListener('click', () => {
            if (socket) {
                socket.disconnect();
                socket = null;
            }
        });
        checkPairingBtn.addEventListener('click', checkPairingStatus);
        forcePairBtn.addEventListener('click', forcePair);
        registerDeviceBtn.addEventListener('click', registerDevice);
        checkRegistrationBtn.addEventListener('click', () => {
            log('🔍 检查注册状态: ' + (socket ? '已连接' : '未连接'));
        });
        sendTestVoiceBtn.addEventListener('click', sendTestVoiceRequest);
        sendTestTextBtn.addEventListener('click', sendTestText);
        startRecordingBtn.addEventListener('click', startRecording);
        stopRecordingBtn.addEventListener('click', stopRecording);
        clearLogBtn.addEventListener('click', clearLog);

        // 页面加载时自动连接
        window.addEventListener('load', () => {
            log('页面加载完成，准备连接服务器...');
            connectToServer();
        });

        // 页面卸载时清理
        window.addEventListener('beforeunload', () => {
            if (socket) {
                socket.disconnect();
            }
        });
    </script>
</body>
</html> 